package com.cr.crsystem.system.controller;


import com.cr.crsystem.common.utils.Result;
import com.cr.crsystem.common.utils.ResultCode;
import com.cr.crsystem.system.entity.User;
import com.cr.crsystem.system.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author su
 * @since 2022-06-21
 */
@CrossOrigin
@Api(tags = "用户管理")
@Slf4j
@RestController
@RequestMapping("/system/user")
public class UserController {
    @Autowired
    private UserService userService;

    @ApiOperation("新增用户")
    @PostMapping("/add")
    public Result<User> add(@RequestBody User registerUser) {
        Result<User> result = new Result<>();
        try {
            // 保存用户走一个service
            User user = userService.saveUser(registerUser);
            result.setResult(user);
            result.setCode(ResultCode.SUCCESS);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error20001("操作失败");
        }
        return result;
    }

    @ApiOperation("修改用户")
    @PostMapping("/edit")
    public Result<User> edit(@RequestBody User user) {
        Result<User> result = new Result<>();
        try {
            User userAfter = userService.getById(user.getId());
            if (userAfter == null) {
                result.error20001("未找到对应实体");
            } else {
                // 修改用户走一个service 保证事务
                userService.editUser(user);
                result.setResult(user);
                result.success("修改成功!");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error20001("操作失败");
        }
        return result;
    }

    @ApiOperation("删除用户")
    @DeleteMapping("/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) Integer id) {
        if (id!=0) {
            if (userService.deleteUser(id)) {
                return Result.OK().success("删除用户成功");
            }
        }
       return Result.error("删除用户失败");
    }

    @ApiOperation("校验账号唯一")
    @GetMapping ("/checkUsername")
    public Result<Boolean> checkUsername(Integer userId, String username) {
        Result<Boolean> result = new Result<>();
        result.setResult(false);
        log.info("--验证账号是否唯一---id:" + userId + "--roleCode:" + username);
        boolean checkName = userService.checkUsername(userId, username);
        if (checkName) {
            result.setResult(true);
            result.success("账号已存在");
            return result;
        }
        return result;
    }
}

